import 'package:comics/pages/home/home.dart';
import 'package:comics/store/store.dart';
import 'package:flutter/cupertino.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../pages/login/login.dart';

final GoRouter router = GoRouter(
    initialLocation: '/home',
    routes: <GoRoute>[
      GoRoute(
        path: '/',
        redirect: (BuildContext context, GoRouterState state) {
          return '/home';
        },
      ),
      GoRoute(
        path: '/home',
        builder: (context, state) => _requireLogin(context, state, () => const Home())
      ),
      GoRoute(
          path: '/login',
          builder: (context, state) => const Login()
      ),
    ]
);

/// 需要登录的组件构建方法
/// @return 组件
typedef _WidgetBuilder = Widget Function();

/// 需要登录的组件
/// @param context 上下文
/// @param state 路由状态
/// @param builder 组件构建方法
/// @return 组件
Widget _requireLogin(BuildContext context, GoRouterState state, _WidgetBuilder builder) {
  final isLogin = context.read<Store>().isLogin;
  if (!isLogin) {
    Future.microtask(() {
      // 重定向到登录页面, 销毁当前所有页面
      //router.go('/login');
    });
    return Container();
  }
  return builder();
}